package cn.acewill.lrz.activeMQ;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**

 */
public class JmsSend {
    public static void main(String[] args) throws Exception {
        JmsSend jms = new JmsSend();
//        jms.queueSend();
        jms.topicSend();
    }

    /**
     * 持久化话题
     */
    private void topicSend() throws Exception{
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
        Connection connection = connectionFactory.createConnection();
        Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
        Topic destination = session.createTopic("MyTopic");
        MessageProducer producer = session.createProducer(destination);
        //持久化订阅
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        //一定要设置完成持久化订阅后， 再start 这个 connection
        connection.start();
        for(int i=0; i<50; i++) {
            TextMessage message = session.createTextMessage("messagedd--"+i);
            Thread.sleep(1000);
            //通过消息生产者发出消息
            producer.send(message);
        }
        session.commit();
        session.close();
        connection.close();
    }

    /**
     * Queue消息发送
     * @throws Exception
     */
    private void queueSend() throws Exception{
        ConnectionFactory connectionFactory = new
                ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
        Connection connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue("my-queue");
        //JMS producer：消息生产者， 创建和发送JMS消息的客户端应用
        MessageProducer producer = session.createProducer(destination);
        for(int i=0; i<3; i++) {
            TextMessage message = session.createTextMessage("message--"+i);
            Thread.sleep(1000);
            //通过消息生产者发出消息
            producer.send(message);
        }
        session.commit();
        session.close();
        connection.close();
    }
}
